<template>
    <div>

<!--        抽屉-->
        <a-button style="margin-bottom: 20px" type="primary" @click="showDrawer(0)"> <PlusOutlined /> 添加 </a-button>
        <a-drawer
                :title="drawerTitle"
                :width="720"
                :visible="visible"
                :body-style="{ paddingBottom: '80px' }"
                @close="onClose"
        >


            <a-form :form="form" layout="vertical" hide-required-mark>
                <!--                名称-->
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="Name">
                            <a-input :disabled="drawerInfo.userNameInput" v-model:value="form.name" placeholder="Please enter user name" />

                        </a-form-item>
                    </a-col>

                </a-row>


                <!--                密码-->
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="密码">
                            <a-input-password  v-model:value="form.password" placeholder="input password" />
                        </a-form-item>
                    </a-col>

                </a-row>

                <!--                确认密码-->
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="确认密码">
                            <a-input-password  v-model:value="form.rePassword" placeholder="input password" />
                            <div v-show="form.password!==form.rePassword" style="display:inline-block;width: 100%;text-align: center;color: red">
                                两次密码不一致
                            </div>
                        </a-form-item>
                    </a-col>

                </a-row>


                <!--                权限-->
                <a-checkbox-group v-model:value="defaultCheckedList"  :options="plainOptions" />


            </a-form>

            <div
                    :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
            >
                <a-button :style="{ marginRight: '8px' }" @click="onClose">
                    取消
                </a-button>
                <a-button type="primary" @click="onSubmit">
                    确定
                </a-button>
            </div>
        </a-drawer>

<!--        表格-->
    <a-table :columns="columns" :data-source="dataSource">


<!--        权限-->
        <template #limits="{ text: limits }">
          <span>
            <a-tag
                    v-for="tag in limits"
                    :key="tag"
                    :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
            >
              {{ tag.lable }}
            </a-tag>
          </span>
        </template>

<!--        操作-->
        <template #action="{ record }">
          <span>
             <a @click="showDrawer(record.id, record.limits)">修改</a>
              <a-divider type="vertical" />

             <a-popconfirm
                     v-if="dataSource.length"
                     title="Sure to delete?"
                     @confirm="onDelete(record.id)"
             >
                <a>Delete</a>
             </a-popconfirm>

            <a-divider type="vertical" />
            <a class="ant-dropdown-link">
              More actions
              <down-outlined />
            </a>
          </span>
        </template>
    </a-table>

    </div>
</template>
<script>

    import { addOrUpdateUser, getUserAll, delUser } from "@/api/user/index"
    import {  message  } from 'ant-design-vue';
    import { PlusOutlined, DownOutlined } from '@ant-design/icons-vue';
    import { defineComponent, ref, reactive, onMounted } from 'vue';
    import md5 from 'js-md5'

    /**
     * 表头
     * */
    const columns = [
        {
            title: '用户',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: 'Email',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: '权限',
            key: 'limits',
            dataIndex: 'limits',
            slots: {
                customRender: 'limits',
            },
        },
        {
            title: '操作',
            key: 'action',
            slots: {
                customRender: 'action',
            },
        },
    ];

    /**
     * 数据源
     * */
    const dataSource =  ref([]);

    /**
     * 权限
     * */
    const plainOptions = [ { label: '读', value: '1' },
        { label: '改', value: '2' },{ label: '超', value: '0' },];


    export default defineComponent({
        setup() {

            /**
             * input
             * */
            const form = reactive({
                name: '',
                password: '',
                rePassword: '',
                updateId: 0
            });

            /**
             * 抽屉  按钮信息 等
             * */
            const drawerInfo = reactive({
                userNameInput: false,
                drawerTitle: "添加管理",
                Submit: "添加",
                updateId: false,

            });
            const visible = ref(false);  //抽屉状态

            const defaultCheckedList = ref([]);  //默认选中 权限


            /**
             * 获取数据
             * */
            const getDataList = ()=> {
                 getUserAll().then(data=>{
                    console.log("userList:",data);
                    if(data.code==200){

                        data.list.forEach(item=>{
                            let tags = [];
                            let limitList = item.limits.split('-');
                            limitList.forEach(item1=>{
                                tags.push({lable: limits(item1), value: item1})
                            });
                            item.limits = tags;
                        });
                        console.log("limits:",data.list);
                        dataSource.value = data.list;
                        console.log(dataSource)
                    }
                })
            };

            /**
             * 权限
             * */
            const limits = limit => {
                switch (limit) {
                    case '0':
                        return '超';
                    case '1':
                        return "读";
                    case '2':
                        return "改";
                    case '3':
                        return "删";
                }
            };

            /**
             * 删除
             * @param key
             */
            const onDelete = key => {
                console.log(key);

                delUser(JSON.stringify({id: key})).then(data=>{
                    if(data.code===200){
                        console.log(data);
                        message.success(data.msg);
                        dataSource.value = dataSource.value.filter(item => item.id !== key);
                    }else{
                        message.error(data.msg);
                    }
                });
            };

            /**
             * 提交
             * */
            const onSubmit = () =>{
                console.log(defaultCheckedList.value);

                console.log('submit!', form);
                if(form.password!==form.rePassword){
                    // return this.$message.error("两次密码不一致!");
                }


                let userName = form.name;
                let password = form.password;
                let updateId = form.updateId;
                password = md5(password); // bcecb35d0a12baad472fbe0392bcc043
                let limit = defaultCheckedList.value;
                let users = {
                    userName, password, limits: limit.join('-')
                };
                if(!password) return message.warning("密码不能为空");
                if(updateId){ //更新
                    users = {
                        id: updateId, password, limits: limit.join('-')
                    };
                }
                addOrUpdateUser(JSON.stringify(users)).then(data=>{
                    console.log("data:",data);
                    if(data.code===200) {
                        message.success(data.msg);
                        getDataList();
                    }
                    else {
                        message.warning(data.msg);
                        // that.getDataList();
                    }
                })

            };


            /**
             * 展开 抽屉
             * */
            const showDrawer = (id, userLimits)=> {

                visible.value = true;

                console.log(id);
                if(id) { //更新
                    form.updateId = id;
                    drawerInfo.userNameInput = 'disabled';
                    drawerInfo.drawerTitle = '修改';
                    drawerInfo.Submit = '更新';
                    drawerInfo.updateId = id
                }
                else {

                    drawerInfo.userNameInput = false;
                    form.name = '';
                    drawerInfo.defaultCheckedList = [];
                    drawerInfo.drawerTitle = '添加管理';
                    drawerInfo.Submit = '添加';
                    drawerInfo.updateId = false
                }

                dataSource.value.forEach(item=>{
                    if(item.id==id){
                        console.log(id)

                        var tags = item.limits;
                        defaultCheckedList.value = tags.map(item2 => {
                            return item2.value;
                        });

                        form.name = item.userName;
                    }
                });

            };


            /**
             * 关闭抽屉
             */
            const onClose = () => {
                visible.value = false;
            };

            /**
             * 生命周期
             */
            onMounted(getDataList); //调用


            return {
                onDelete,
                dataSource,
                columns,
                showDrawer,
                drawerInfo,
                visible,
                form,
                onClose,
                defaultCheckedList,
                plainOptions,
                onSubmit,
                getDataList
            };
        },

        components: {
            PlusOutlined,
        },

    });
</script>
